//
//  ProgressView.m
//  CoreAnimation
//
//  Created by LG on 2018/5/18.
//  Copyright © 2018年 iqiyi. All rights reserved.
//

#import "ProgressView.h"

@interface ProgressView ()
{
    CGFloat _innerDefaultLineWidth;
    CGColorRef _innerDefaultLineColor;
}

@property (nonatomic, strong) CAShapeLayer *shapeLayer;

@end

@implementation ProgressView

+ (Class)layerClass
{
    return [CAShapeLayer class];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        _innerDefaultLineColor = [[UIColor blackColor]CGColor];
        _innerDefaultLineWidth = 10.;
        
        ((CAShapeLayer*)self.layer).fillColor = [UIColor clearColor].CGColor;
        ((CAShapeLayer*)self.layer).lineWidth = _innerDefaultLineWidth;
        ((CAShapeLayer*)self.layer).strokeColor = _innerDefaultLineColor;
        ((CAShapeLayer*)self.layer).path = [self bezierCirclePath].CGPath;
        ((CAShapeLayer*)self.layer).lineCap = kCALineCapRound;
    }
    return self;
}

#pragma mark -- function
- (void)needsLayoutProgress
{
    ((CAShapeLayer*)self.layer).lineWidth = self.lineWidth>0?:_innerDefaultLineWidth;
    ((CAShapeLayer*)self.layer).strokeColor = [self.lineColor CGColor] ? : _innerDefaultLineColor;
    ((CAShapeLayer*)self.layer).path = [self bezierCirclePath].CGPath;
    ((CAShapeLayer*)self.layer).strokeStart = 0.;
    ((CAShapeLayer*)self.layer).strokeEnd = 0.;
}

#pragma mark -- Public

- (void)updateProgress:(CGFloat)progress
{
//    NSAssert(progress < 0 || progress > 1, @"进度值不合法");
    ((CAShapeLayer*)self.layer).strokeEnd = progress;
}

- (void)setRadiousCircle:(CGFloat)radiousCircle
{
    _radiousCircle = radiousCircle;
    
    [self needsLayoutProgress];
}

- (void)setLineColor:(UIColor *)colorCircle
{
    _lineColor = colorCircle;
    
    [self needsLayoutProgress];
}

- (void)setWidthLine:(CGFloat)widthLine
{
    _lineWidth = widthLine;
    
    [self needsLayoutProgress];
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
    [self needsLayoutProgress];
}

#pragma mark -- Tools

- (UIBezierPath*)bezierCirclePath
{
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithArcCenter:self.center
                                                              radius:self.radiousCircle?:CGRectGetHeight(self.bounds)
                                                          startAngle:-M_PI_2
                                                            endAngle:M_PI + M_PI_2
                                                           clockwise:YES];
    
    return bezierPath;
}

@end
